package com.sita.cfmoto.interact.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.sita.cfmoto.R;
import com.sita.cfmoto.support.GlobalContext;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LocationPoiActivity extends AppCompatActivity {
    @Bind(R.id.poi_list)
    ListView poiList;
    @Bind(R.id.search_edit)
    EditText searchEdit;
    @Bind(R.id.search_cancel_btn)
    Button searchCancel;

    private PoiSearch.Query query;// Poi查询条件类
    private String deepType = "";// poi搜索类型
    private int currentPage = 0;// 当前页面，从0开始计数
    private LatLonPoint latLonPoint = new LatLonPoint(39.908127, 116.375257);// 默认西单广场
    private PoiSearch poiSearch;
    private PoiResult poiResult; // poi返回的结果
    private List<PoiItem> poiItems = new ArrayList<>();// poi数据
    //    private List<String> poiItemData = new ArrayList<>();
    private ArrayAdapter adapter;
    private String mCity;
    private String mStreet;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_poi);
        ButterKnife.bind(this);
        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        latLonPoint.setLatitude(location.getLatitude());
        latLonPoint.setLongitude(location.getLongitude());
        mCity = location.getCity();
        mStreet = location.getStreet();
        adapter = new ArrayAdapter<>(this, R.layout.item_poi_search, poiItems);
        poiList.setAdapter(adapter);
        poiList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                PoiItem item = poiItems.get(position);
                if (item.getLatLonPoint() != null) {
                    bundle.putString("myLocation", item.getTitle());
                    bundle.putDouble("lat", item.getLatLonPoint().getLatitude());
                    bundle.putDouble("lng", item.getLatLonPoint().getLongitude());
                }
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        doSearchQuery(mCity, adapter);
        searchCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchEdit.setText("");
//                poiItemData.clear();
                doSearchQuery(mCity, adapter);
            }
        });
        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String location_key = searchEdit.getText().toString();
                query = new PoiSearch.Query(location_key, "", mCity);
                query.setPageSize(10);// 设置每页最多返回多少条poiitem
                query.setPageNum(currentPage);//设置查询页码
                poiSearch = new PoiSearch(getApplicationContext(), query);//初始化poiSearch对象
                poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                                                     @Override
                                                     public void onPoiSearched(PoiResult result, int rCode) {
                                                         if (rCode == 1000) {
                                                             if (result != null && result.getQuery() != null) {// 搜索poi的结果
                                                                 if (result.getQuery().equals(query)) {// 是否是同一条
                                                                     setData(result.getPois());
                                                                     List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                                                                 }
                                                             }
                                                         }
                                                     }

                                                     @Override
                                                     public void onPoiItemSearched(PoiItem poiItem, int i) {

                                                     }
                                                 }
                );//设置回调数据的监听器
                poiSearch.searchPOIAsyn();//开始搜索
            }
        });

    }


//    class PoiSearch implements View.OnClickListener,

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(String city, final ArrayAdapter arrayadapter) {
        currentPage = 0;
        query = new PoiSearch.Query("", "", city);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页
        if (latLonPoint != null) {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
                @Override
                public void onPoiSearched(PoiResult result, int rCode) {
                    if (rCode == 1000) {
                        if (result != null && result.getQuery() != null) {// 搜索poi的结果
                            if (result.getQuery().equals(query)) {// 是否是同一条
                                setData(result.getPois());
                            }
                        }
                    }
                }

                @Override
                public void onPoiItemSearched(PoiItem poiItem, int i) {

                }
            });
            poiSearch.setBound(new PoiSearch.SearchBound(latLonPoint, 2000, true));//
            // 设置搜索区域为以lp点为圆心，其周围2000米范围
            poiSearch.searchPOIAsyn();// 异步搜索
        }
    }

    private synchronized void setData(List<PoiItem> items) {
        Handler handler = new Handler(this.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {

                poiItems.clear();

                PoiItem noLocationItem = new PoiItem(getString(R.string.dynamic_no_location),
                        null, getString(R.string.dynamic_no_location), null);
                poiItems.add( noLocationItem);

                if (items.size() > 0) {
                    String city = items.get(0).getCityName();
                    PoiItem cityItem = new PoiItem(null,
                            latLonPoint, city, null);
                    poiItems.add(cityItem);
                    if (city.equals(mCity)) {
                        PoiItem cityStreetItem = new PoiItem(null,
                                latLonPoint, city + mStreet, null);
                        poiItems.add(cityStreetItem);
                    }
                    poiItems.addAll(items);
                }
                adapter.notifyDataSetChanged();
            }
        });
    }

    @OnClick(R.id.back_img)
    void onClickBack() {
        finish();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
